package net;

/**
 * @author Ajie
 * @date 7/4/24
 * @function
 */
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;

import java.io.IOException;

public class SimpleFTPClient {
    public static void main(String[] args) {
        FTPClient ftpClient = new FTPClient();
        try {
            ftpClient.connect("39.100.126.26", 21);
            ftpClient.login("wismed", "wismed1234");

            int replyCode = ftpClient.getReplyCode();
            if (!FTPReply.isPositiveCompletion(replyCode)) {
                System.out.println("Failed to connect to the server. FTP server refused connection.");
                return;
            }

            System.out.println("Connected and logged in to the server.");

//            ftpClient.enterLocalPassiveMode();
            //结果：
            //Connected and logged in to the server.
            //An error occurred: Connection refused (Connection refused)
            //java.net.ConnectException: Connection refused (Connection refused)
            //	at java.base/java.net.PlainSocketImpl.socketConnect(Native Method)
            //	at java.base/java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:412)
            //	at java.base/java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:255)
            //	at java.base/java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:237)
            //	at java.base/java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
            //	at java.base/java.net.Socket.connect(Socket.java:609)
            //	at org.apache.commons.net.ftp.FTPClient._openDataConnection_(FTPClient.java:866)
            //	at org.apache.commons.net.ftp.FTPClient._openDataConnection_(FTPClient.java:711)
            //	at org.apache.commons.net.ftp.FTPClient.listNames(FTPClient.java:2761)
            //	at net.SimpleFTPClient.main(SimpleFTPClient.java:35)

//            ftpClient.enterLocalActiveMode();
            //Connected and logged in to the server.
            //Failed to list files or no files found.

            // List files in the root directory to ensure connection
            String[] files = ftpClient.listNames("/");
            if (files != null && files.length > 0) {
                for (String file : files) {
                    System.out.println("File: " + file);
                }
            } else {
                System.out.println("Failed to list files or no files found.");
            }

        } catch (IOException ex) {
            System.out.println("An error occurred: " + ex.getMessage());
            ex.printStackTrace();
        } finally {
            try {
                if (ftpClient.isConnected()) {
                    ftpClient.logout();
                    ftpClient.disconnect();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
}
